package br.upe.dsc.caeto.simulation;

import br.upe.dsc.caeto.core.application.Application;
import br.upe.dsc.caeto.core.project.Project;
import br.upe.dsc.caeto.core.CaetoManager;
import br.upe.dsc.caeto.core.ElementNotFoundException;
import br.upe.dsc.caeto.core.InvalidElementException;

import java.util.Iterator;

import org.jdesktop.application.Task;

public class Simulator extends Task<Void, Void> {
    private String projectName;
    private org.jdesktop.application.Application desktopApplication;

    public Simulator(org.jdesktop.application.Application desktopApplication,
                     String projectName) {
        super(desktopApplication);
        this.desktopApplication = desktopApplication;
        this.projectName = projectName;
    }

    @Override protected Void doInBackground() {
        CaetoManager caeto = CaetoManager.getInstance();
        Simulation simulation;
        SimulatorTask simulatorTask;
        try {
	        Project project = caeto.search(projectName);
	        Iterable<Application> applications = project.getApplications();
	        
	        for (Application application : applications) {
	        	if (application.getTipoSimulacao().equals("SimpleSimulation")) {
		            simulation = new SimpleSimulation(application);
		            simulatorTask = new SimulatorTask(desktopApplication,
		            	simulation);
		            simulatorTask.execute();
	        	}
	        }
        }
        catch (ElementNotFoundException e) {
        	//
        }
        return null;
    }

    private class SimulatorTask extends Task<Void, Void> {
        Simulation simulation;

        public SimulatorTask(org.jdesktop.application.Application application,
                             Simulation simulation) {
            super(application);
            this.simulation = simulation;
        }

        @Override protected Void doInBackground() {
            simulation.start(); 
            return null;
        }
    }
}
